from datetime import date, timedelta
from django.db import connection
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.goods.models import GoodsVisitCount
from apps.orders.models import OrderInfo
from apps.users.models import User


def get_mysql_data(sql):
    with connection.cursor() as cursor:
        cursor.execute(sql)
        data = cursor.fetchall()
        # print(type(data), data)

    # connection.close()
    return data


# 用户总量统计
class UserCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        date_now = date.today()
        count = User.objects.filter(is_staff=False, is_active=True).count()
        return Response({"count": count, "date": date_now})


# 当天注册用户总量统计
class UserDayCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        date_now = date.today()
        # count = User.objects.filter(is_staff=False, is_active=True, date_joined__gte=date_now).count()
        sql = f"SELECT COUNT(*) FROM `tb_users` WHERE `is_staff`=FALSE AND `date_joined`>='{date_now}'"
        data = get_mysql_data(sql)
        count = data[0][0]
        return Response({"count": count, "date": date_now})


# 当天登录用户总量统计
class UserDayActiveCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        date_now = date.today()
        # count = User.objects.filter(last_login__gte=date_now, is_staff=False, is_active=True).count()

        sql = f"SELECT COUNT(*) FROM `tb_users` WHERE `last_login`>='{date_now}' AND `is_staff`=FALSE"
        data = get_mysql_data(sql)
        count = data[0][0]

        return Response({"count": count, "date": date_now})


# 当天下单用户总量统计
class UserDayOrderCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        date_now = date.today()
        count = OrderInfo.objects.values('user_id').filter(create_time__gte=date_now).distinct().count()
        return Response({"count": count, "date": date_now})


# 月增用户总量统计
class UserMonthCountView(APIView):
    permission_classes = [IsAdminUser]


    def get(self, request):
        # end_date = date.today()
        # start_date = end_date - timedelta(days=29)
        # month_users = User.objects.filter(is_staff=False, is_active=True, date_joined__gte=start_date)
        # date_lst = []
        # cur_date = start_date
        # next_date = start_date + timedelta(1)
        # for i in range(30):
        #     count = month_users.filter(date_joined__gte=cur_date, date_joined__lt=next_date).count()
        #     date_lst.append({"count": count, "date": cur_date})
        #     cur_date += timedelta(1)
        #     next_date += timedelta(1)
        # return Response(date_lst)
        # 上面的太慢了,用原生sql执行

        start_date = date.today() - timedelta(29)
        data_dict = dict()
        sql = f"SELECT DATE_FORMAT(`date_joined`,'%Y-%m-%d') AS days," \
              f"COUNT(*) AS incre_count " \
              f"FROM `tb_users` WHERE " \
              f"`is_staff`=FALSE AND" \
              f"`date_joined` > '{start_date}' " \
              f"GROUP BY days;"
        for i in range(30):
            data_dict[str(start_date)] = 0
            start_date += timedelta(1)

        data = get_mysql_data(sql)

        data_dict.update(data)
        data_list = [{"count": v, "date": k} for k, v in data_dict.items()]
        return Response(data_list)


# 商品分类访问量统计
class GoodsCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        date_now = date.today()
        visit_lst = [{"category": goods_visit.category.name, "count": goods_visit.count} for goods_visit in
                     GoodsVisitCount.objects.filter(create_time__gte=date_now)]
        return Response(visit_lst)
